package com.cloudweb.oa.util;

import com.cloudweb.oa.utils.SpringUtil;
import com.redmoon.oa.android.Constant;
import cn.js.fan.security.ThreeDesUtil;
import cn.js.fan.util.ParamUtil;
import cn.js.fan.util.StrUtil;
import com.redmoon.oa.LogDb;
import com.redmoon.oa.android.CloudConfig;
import com.redmoon.oa.person.UserDb;
import com.redmoon.oa.sys.DebugUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;

public class AuthUtil {

    public static final int ERR_USER_EMPTY = 0;

    public static final int ERR_USER_INVALID = -1;

    private int errCode;

    private String errMsg;

	public boolean isUserLogin(HttpServletRequest request) {
		HttpSession session = request.getSession(true);
		String name = (String) session.getAttribute(Constant.OA_NAME);
		return name != null;
	}

    // 判断skey是否过期
    public boolean auth(HttpServletRequest request) {
        String skey = ParamUtil.get(request, "skey");
        if (!StringUtils.isEmpty(skey)) {
            CloudConfig cloudConfig = CloudConfig.getInstance();
            String str = ThreeDesUtil.decrypthexstr(cloudConfig.getProperty("key"), skey);
            int index = str.lastIndexOf("|");
            String otime = str.substring(index + 1, str.length());
            Date now = new Date();
            long defTime = now.getTime();
            long time = now.getTime() - StrUtil.toLong(otime, defTime);
            long time1 = time / 1000 / 60;
            if (time1 > 20) {
                return true;
            }
        }

        // 如果已经登录，则不需要再验证，便于PC端测试
        if (isUserLogin(request)) {
            /*HttpSession session = request.getSession(true);
            userName = (String) session.getAttribute(Constant.OA_NAME);*/
            return true;
        }

        String userName = getUserName(skey);
        if (StringUtils.isEmpty(userName)) {
            errCode = ERR_USER_EMPTY;
            return false;
        }

        // 判断帐户是否已被停用
        UserDb user = new UserDb();
        user = user.getUserDb(userName);
        if (!user.isValid()) {
            errCode = ERR_USER_INVALID;
            errMsg = "帐户已被停用";
            return false;
        }

        doLoginByUserName(request, userName);

        return true;
    }

    // 取得用户名
    public String getUserName(String skey) {
        String userName = "";
        if (skey != null && !skey.equals("")) {
            String url;
            // url = new String(Base64.decodeBase64(skey.getBytes()));
            CloudConfig cloudConfig = CloudConfig.getInstance();
            url = ThreeDesUtil.decrypthexstr(cloudConfig.getProperty("key"), skey);
            int index = url.indexOf("|");
            if (index == -1) {
                return "";
            }
            userName = url.substring(0, index);
        }
        return userName;
    }

    public void doLoginByUserName(HttpServletRequest request, String userName) {
        UserDb user = new UserDb();
        user = user.getUserDb(userName);

        HttpSession session = request.getSession();
        session.setAttribute(Constant.OA_NAME, userName);
        session.setAttribute(Constant.OA_UNITCODE, user.getUnitCode());

        // spring security 手工认证
        UserDetailsService userDetailsService = SpringUtil.getBean(UserDetailsService.class);
        //根据用户名username加载userDetails
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        //根据userDetails构建新的Authentication,这里使用了
        //PreAuthenticatedAuthenticationToken当然可以用其他token,如 UsernamePasswordAuthenticationToken              
        /*PreAuthenticatedAuthenticationToken authentication =
                new PreAuthenticatedAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());*/

        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userName, userDetails.getPassword(), userDetails.getAuthorities());
        //设置authentication中details
        authentication.setDetails(new WebAuthenticationDetails(request));
        //存放authentication到SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(authentication);
        //在session中存放security context,方便同一个session中控制用户的其他操作
        session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext());
    }

    public String getErrMsg() {
        return errMsg;
    }

    public int getErrCode() {
        return errCode;
    }
}
